trigger OpportunitySharingTrigger on Opportunity (after insert, after update) {

    
               
    Map<ID,ID> posIdToNewMgrIdMap = new Map<ID,ID>();           
 
    List<sObject> sharesToInsert = new List<sObject>(); 
    
    for (Opportunity position:Trigger.new){
      
        if (Trigger.isUpdate){
           
            if(position.Manager__c != Trigger.oldMap.get(position.Id).Manager__c){
                posIdToNewMgrIdMap.put(position.Id,position.Manager__c);
            }           
        }
       
        if (Trigger.isInsert 
             || position.StageName!= Trigger.oldMap.get(position.Id).StageName
             || position.Type!= Trigger.oldMap.get(position.Id).Type
             || position.Manager__c != Trigger.oldMap.get(position.Id).Manager__c) {
            OpportunityShare positionShare = new OpportunityShare(OpportunityId = position.Id
                                                 , userOrGroupId = position.Manager__c
                                                 );
            if ((position.StageName == 'Qualification') && (position.Type=='New Customer')){
                positionShare.OpportunityAccessLevel = 'Edit';                                         
            } else {
                positionShare.OpportunityAccessLevel = 'Read';
           }
           sharesToInsert.add(positionShare);
        }
    }

    if (posIdToNewMgrIdMap!=null && posIdToNewMgrIdMap.size() > 0 ) {
        OpportunitySharingClass.deleteOpportunitySharingByRowCause(posIdToNewMgrIdMap, 'Manager__c');      
    }
    
    Database.insert(sharesToInsert);        
}